package com.transaction.stockseata.interceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.transaction.stockseata.annoation.RepeatSubmit;
import com.transaction.stockseata.utils.RedisCache;
import com.transaction.stockseata.utils.RepeatedlyRequestWrapper;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author ausu
 * @version 1.0
 * @description: TODO
 * @date 2023/1/29 21:41
 */
@Component
public class SameUrlDataInterceptor extends RepeatSubmitInterceptor{
    public static final String REPEAT_PARAMS = "repeatParams";

    public static final String REPEAT_TIME = "repeat_Time";

    public static final String REPEAT_SUBMIT_KEY = "REPEAT_SUBMIT_KEY";

    private String header = "Authorization";

    @Autowired
    private RedisCache redisCache;

    /**
     * 验证是否重复提交由子类实现具体的防重复提交的规则
     *
     * @param request
     * @param annotation
     * @return
     */
    @SuppressWarnings("unchecked")
    @Override
    public boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation) {
        String nowParams = "";
        if (request instanceof RepeatedlyRequestWrapper) {
          RepeatedlyRequestWrapper  repeatedlyRequestWrapper= (RepeatedlyRequestWrapper) request;
            try {
                nowParams = repeatedlyRequestWrapper.getReader().readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // body参数为空， 获取Parameter的数据
        if (StringUtils.isEmpty(nowParams)) {
            try {
                nowParams = new ObjectMapper().writeValueAsString(request.getParameterMap());
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        HashMap<String, Object> nowDataMap = Maps.newHashMap();
        nowDataMap.put(REPEAT_PARAMS,nowParams);
        nowDataMap.put(REPEAT_TIME,System.currentTimeMillis());

        // 请求地址 （作为存放cache的key）
        String uri = request.getRequestURI();

        // 唯一值（没有消息头则使用请求地址）
        String submitKey = request.getHeader(this.header);

        // 唯一标识 （指定Key + uri + 消息头）
       String cacheRepeatKey = REPEAT_SUBMIT_KEY + uri + submitKey;

        Object sessionObj = redisCache.getCacheObject(cacheRepeatKey);
        if (sessionObj != null) {

        }

        return false;
    }
}
